// wigets/business/luckdraw/index.js
import {
  squared
} from "../../../js/modules/game.js";
import {
  storage,
  util,
  dialog,
  api
} from '../../../js/util';
import {
  router
} from '../../../js/router';
import {
  address
} from '../../../js/modules/store';
import authorize from "../../../js/modules/authorize"
const componentBehavior = require('../../../js/common/ComponentBehavior')

Component({
  behaviors: [componentBehavior],
  lifetimes: {
    attached() {
      // 动态设置scroll区域高度
      let system = wx.getSystemInfoSync()
      let rpxHeight = system.windowHeight * 750 / system.windowWidth
      this.setData({
        scrollHeight: rpxHeight - 100
      })
    },
    detached() {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  /**
   * 组件的属性列表
   */
  properties: {
    id:{
      value: 0,
      type: Number
    },
    type: {
      value: 0,
      type: Number
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    isShowPage:false,
    isOrderDraw: 0,
    storeId: 0,
    drawIndex: -1, //转动元素索引
    count: 3, //游戏次数
    winlist: [], //中奖名单
    prize: [],
    last_index: 0, //上一回滚动的位置
    roll_flag: true, //是否允许滚动
    max_number: 7, //轮盘的全部数量
    speed: 300, //速度，速度值越大，则越慢 初始化为300
    max_speed: 40, //滚盘的最大速度
    minturns: 8, //最小的圈数为2
    showShadow: false,
    showShadowRule: false, //游戏说明弹层
    showShadowWin: false, //中奖弹层
    showShadowFail: false, //未中奖弹层
    showShadowInfo: false, //提交信息弹层
    role: "store",
    info: {},
    forms: {
      ContactMan: {
        value: "",
        validate: "isnull",
        error: "请输入您的姓名"
      },
      ContactTel: {
        value: "",
        validate: "isnull|mobile",
        error: "请输入正确的手机号"
      },
      ContactAddress: {
        value: "",
        validate: "isnull",
        error: "请输入你的联系地址"
      }
    },
    scrollHeight: '800'
  },

  /**
   * 组件的方法列表
   */
  methods: {
    initLuckDraw(options) {
      var that = this;
      if(!options.id || options.id==0){
        util.tips("参数错误！");
        return;
      }
      this.setData({
        id: options.id || 0,
        isOrderDraw: options.IsOrderDraw || 0,
        storeId: options.StoreId || 0,
      }, () => {
        that.getGameInfo();
        that.getWinningRecord();
        that.getNearInfo();
      });
    },
    /**显示抽奖弹层 */
    showLuckDrawModal(options) {
      this.initLuckDraw(options);
      dialog.showModal(this, 'showModalStatus')
    },
    /**隐藏抽奖弹层 */
    closeLuckDrawModal() {
      dialog.hideModal(this, 'showModalStatus')
    },
    /**
     * 获得游戏信息
     */
    getGameInfo() {
      var that = this;
      squared.getGameInfo({
        id: this.data.id
      }, function(content) {
        that.setData({
          prize: content.GamePrizes,
          count: content.SurplusCount,
          info: content
        });
        that.setData({
          richtext_gameDescr: content.Descr
        })
      });
    },
    /**
     * 获得中奖记录
     */
    getWinningRecord() {
      var that = this;
      squared.getWinningRecord({
        id: this.data.id
      }, function(content) {
        let arry = [];
        for (let i = 0; i < content.length; i += 5) {
          arry.push(content.slice(i, i + 5));
        };
        that.setData({
          winlist: arry
        })
      });
    },
    /**
     * 获取默认中奖者信息
     */
    getNearInfo(){
      let that = this;
      let {forms} = that.data;
      squared.getNearInfo((res)=>{
        let {ContactAddress,ContactMan,ContactTel,AwardTime} = res;
        if(AwardTime==''){
          address.getDefaultAddress(function(ads){
            if (ads!=undefined&&Object.keys(ads).length>0) {
              forms.ContactMan.value = ads.Name;
              forms.ContactTel.value = ads.Mobile;
              forms.ContactAddress.value = ads.Province + ads.City + ads.Area + ads.Address;
              that.setData({ forms: forms });
            }
          })
        }else{
          forms.ContactMan.value = ContactMan;
          forms.ContactTel.value = ContactTel;
          forms.ContactAddress.value = ContactAddress;
          that.setData({
            forms:forms
          })
        }
      })
    },
    /**
     * 获取预置信息
     */
    getPreInfo() {
      var that = this;
      squared.getGameInfo({
        id: this.data.id
      }, function(content) {
        that.setData({
          preInfo: content
        })
      });
    },
    //开始滚动
    startrolling: function() {
      let _this = this;
      if (!_this.data.roll_flag) {
        return;
      }
      //暂停
      clearTimeout(this.data.timer);
      if (_this.data.info.UsableMode != 2) {
        var count = this.data.count;
        if (count == 0) {
          this.setData({
            drawIndex: -1,
            second: -1
          })
          wx.showToast({
            title: '机会用完啦！',
            icon: 'none',
            duration: 2000
          })
          return;
        }
      }

      squared.getPreInfo({
        id: this.data.id,
        isOrderDraw: this.data.isOrderDraw,
        storeId: this.data.storeId,
      }, function(content) {
        _this.setData({
          preInfo: content
        });
        //初始化步数
        _this.data.runs_now = 0;
        _this.data.drawIndex = 0;
        //当前可以点击的状态下
        if (_this.data.roll_flag) {
          _this.data.roll_flag = false;
          try{
            //启动滚盘
            _this.rolling();
          }
          catch(error){
            clearTimeout(this.data.timer);
            console.log("游戏："+error.message);
          }

        }
      });

    },

    //滚动轮盘的动画效果
    rolling: function() {
      var _this = this;
      this.data.timer = setTimeout(function() {
        _this.rolling();
      }, this.data.speed);
      this.data.runs_now++; //已经跑步数加一
      this.data.drawIndex++; //当前的加一
      //获取总步数，接口延迟问题，所以最后还是设置成1s以上
      var count_num = this.data.minturns * this.data.max_number + Math.ceil(Math.random() * 40) - this.data.last_index;
      if (this.data.drawIndex > this.data.max_number) { //判定！是否大于最大数
        this.data.drawIndex = 0;
      }
      //上升期间
      if (this.data.runs_now <= (count_num / 3) * 2) {
        this.data.speed -= 30; //加速
        if (this.data.speed <= this.data.max_speed) {
          this.data.speed = this.data.max_speed; //最高速度为40；
        }
      }
      //抽奖结束
      else if (this.data.runs_now >= count_num && this.data.preInfo.PrizeId == this.data.prize[this.data.drawIndex].Id) {
        clearTimeout(this.data.timer);
        this.data.roll_flag = true;
        this.data.last_index = this.data.drawIndex;
        this.data.count--;
        var gamePrize = this.data.prize[this.data.drawIndex];
        
        var prize_type = "Win";
        if (gamePrize.PrizeType == 3) {
          prize_type = "Fail";
        }
        this.data.prizeType = gamePrize.PrizeType;
        this.setData(this.data);
        this.showPrizeShadow(prize_type);
        return;
      }
      //下降期间
      else if (count_num - this.data.runs_now <= 10) {
        this.data.speed += 20;
      }
      //缓冲区间
      else {
        this.data.speed += 10;
        if (this.data.speed >= 100) {
          this.data.speed = 100; //最低速度为100；
        }
      }


      this.setData(this.data);

    },
    /**
     * 领取奖品
     */
    onAwardEvent: function() {
      this.closeShadow();
      this.showPrizeShadow("Info");
    },
    /**
     * 领取奖品事件
     */
    onReceivedAwardEvent: function() {
      var that = this;
      if (!authorize.isLogin(this.data.role)) {
        authorize.redirect(this.data.role);
        return;
      }
      squared.submitReceivedAward(this.data.forms, this.data.preInfo, function() {
        that.closeShadow();
      });
    },
    /**
     * 表单值绑定
     */
    bindFormValue: function(e) {
      this.data.forms[e.target.id].value = e.detail.value;

    },
    /**
     * 打开说明弹层
     */
    showShaow: function() {
      this.setData({
        showShadow: true,
        showShadowRule: true
      })
    },
    /**
     * 打开抽奖弹层
     */
    showPrizeShadow: function(name) {
      var shadow = "showShadow" + name;
      this.setData({
        showShadow: true,
        [shadow]: true
      })
    },
    /**
     * 关闭弹层
     */
    closeShadow: function() {
      this.setData({
        showShadow: false,
        showShadowRule: false,
        showShadowWin: false,
        showShadowFail: false,
        showShadowInfo: false
      });
      this.getWinningRecord();
    },
    /**
     * 中奖纪录
     */
    goRecord: function() {
      router.navigate({
        path:"gameRecordList"
      })
    }
  }
})